import Constants

import numpy as np

import tkinter as tk
import threading
import ttkbootstrap
from ttkbootstrap.constants import *

from Utils import logger


def get_screen_resolution() -> (int, int):
    """
    功能: 获取屏幕的分辨率
    参数:
    返回值:- 元组类型，包含分辨率的宽度和高度
    """
    from ctypes import windll
    user32 = windll.user32  # 引入Win32的user32.dll
    gdi32 = windll.gdi32  # 引入Win32的gdi32.dll
    dc = user32.GetDC(None)  # 获取当前显示器的设备上下文句柄
    width = gdi32.GetDeviceCaps(dc, 118)  # 获取显示器的原始分辨率宽度
    height = gdi32.GetDeviceCaps(dc, 117)  # 获取显示器的原始分辨率高度
    user32.ReleaseDC(None, dc)  # 释放设备上下文句柄
    return width, height  # 返回元组类型的分辨率宽度和高度


class DebugWindowUI(ttkbootstrap.Frame):
    def __init__(self, root):
        super().__init__(root)
        font = ("Microsoft YaHei", 10, "bold")

        frame_top1 = ttkbootstrap.Frame(root)
        frame_top1.pack(side=TOP, fill=X, expand=False, padx=10, pady=10)

        label = tk.Label(frame_top1, text="飞行/正常移动模式:", font=font)
        label.pack(side=LEFT, expand=False, padx=5, pady=5)

        self.fly_mode = ttkbootstrap.IntVar()
        self.mode_text = ttkbootstrap.StringVar()
        self.mode_text.set("正常移动模式")
        self.fly_mode_btn = ttkbootstrap.Checkbutton(
            frame_top1,
            textvariable=self.mode_text,
            variable=self.fly_mode,
            onvalue=1, offvalue=0,
            style="success-round-toggle")
        self.fly_mode_btn.pack(side=LEFT, expand=False, padx=5, pady=5)

        self.teleport_origin_btn = tk.Button(frame_top1, text="传送回原点")
        self.teleport_origin_btn.pack(side=LEFT, expand=False, padx=15, pady=5)

        frame_top2 = ttkbootstrap.Frame(root)
        frame_top2.pack(side=TOP, fill=X, expand=False, padx=10, pady=10)

        label = tk.Label(frame_top2, text="传送至坐标:", font=font)
        label.pack(side=LEFT, expand=False, padx=5, pady=5)

        label = tk.Label(frame_top2, text="x:")
        label.pack(side=LEFT, expand=False, pady=5)

        self.entry_x = tk.Entry(frame_top2, width=5)
        self.entry_x.pack(side=LEFT, expand=False, padx=(0, 10), pady=5)

        label = tk.Label(frame_top2, text="y:")
        label.pack(side=LEFT, expand=False, pady=5)
        self.entry_y = tk.Entry(frame_top2, width=5)
        self.entry_y.pack(side=LEFT, expand=False, padx=(0, 10), pady=5)

        label = tk.Label(frame_top2, text="z:")
        label.pack(side=LEFT, expand=False, pady=5)
        self.entry_z = tk.Entry(frame_top2, width=5)
        self.entry_z.pack(side=LEFT, expand=False, padx=(0, 10), pady=5)

        self.teleport_btn = tk.Button(frame_top2, text="传送")
        self.teleport_btn.pack(side=LEFT, expand=False, padx=5, pady=5)

        frame_top3 = ttkbootstrap.Frame(root)
        frame_top3.pack(side=TOP, fill=X, expand=False, padx=10, pady=10)

        label = tk.Label(frame_top3, text="获得物品:", font=font)
        label.pack(side=LEFT, expand=False, padx=5, pady=5)
        label = tk.Label(frame_top3, text="ID:")
        label.pack(side=LEFT, expand=False, padx=0, pady=5)
        self.entry_id = tk.Entry(frame_top3, width=5)
        self.entry_id.pack(side=LEFT, expand=False, padx=(0, 10), pady=5)

        label = tk.Label(frame_top3, text="数量:")
        label.pack(side=LEFT, expand=False, pady=5)
        self.entry_amount = tk.Entry(frame_top3, width=5)
        self.entry_amount.pack(side=LEFT, expand=False, padx=(0, 10), pady=5)

        self.get_item_btn = tk.Button(frame_top3, text="获取物品")
        self.get_item_btn.pack(side=LEFT, expand=False, padx=5, pady=5)

        frame_top4 = ttkbootstrap.Frame(root)
        frame_top4.pack(side=TOP, fill=X, expand=False, padx=10, pady=10)

        label = tk.Label(frame_top4, text="修改玩家移动速度:", font=font)
        label.pack(side=LEFT, expand=False, padx=5, pady=5)

        self.entry_speed = tk.Entry(frame_top4, width=5)
        self.entry_speed.pack(side=LEFT, expand=False, padx=5, pady=5)

        self.speed_btn = tk.Button(frame_top4, text="确认修改")
        self.speed_btn.pack(side=LEFT, expand=False, padx=5, pady=5)

        frame_top5 = ttkbootstrap.Frame(root)
        frame_top5.pack(side=TOP, fill=X, expand=False, padx=10, pady=10)

        label = tk.Label(frame_top5, text="修改玩家最大触碰范围:", font=font)
        label.pack(side=LEFT, expand=False, padx=5, pady=5)

        self.entry_max_distance = tk.Entry(frame_top5, width=5)
        self.entry_max_distance.pack(side=LEFT, expand=False, padx=5, pady=5)

        self.max_distance_btn = tk.Button(frame_top5, text="确认修改")
        self.max_distance_btn.pack(side=LEFT, expand=False, padx=5, pady=5)

        frame_top6 = ttkbootstrap.Frame(root)
        frame_top6.pack(side=TOP, fill=X, expand=False, padx=10, pady=10)

        label = tk.Label(frame_top6, text="开启/关闭墙壁传统:", font=font)
        label.pack(side=LEFT, expand=False, padx=5, pady=5)

        self.through_walls_mode = ttkbootstrap.IntVar()
        self.through_walls_mode.set(Constants.ThroughWalls)
        self.through_walls_text = ttkbootstrap.StringVar()
        self.through_walls_text.set(f"默认{Constants.ThroughWalls}")
        self.through_walls_btn = ttkbootstrap.Checkbutton(
            frame_top6,
            textvariable=self.through_walls_text,
            variable=self.through_walls_mode,
            onvalue=1, offvalue=0,
            style="success-round-toggle")
        self.through_walls_btn.pack(side=LEFT, expand=False, padx=5, pady=5)


class DebugWindow(DebugWindowUI):
    def __init__(self, kwargs):
        self.kwargs = kwargs
        logger.info('已启动调试窗口')

        self.root = ttkbootstrap.Window()
        self.root.title("调试窗口")
        self.window_init_position(800, 400)  # 设置窗口初始位置,默认是在右下角

        self.root.attributes('-topmost', True)  # 置顶窗口

        super().__init__(self.root)
        self.component_init()
        self.events_register()

    def window_init_position(self, width=800, height=400) -> None:
        """设置窗口初始位置"""
        screen_width, screen_height = get_screen_resolution()
        self.root.geometry(f"{width}x{height}+{screen_width - width}+{screen_height - height}")

    def component_init(self):
        """组件初始化"""
        self.entry_speed.insert(0, str(Constants.MOVE_SPEED))
        self.entry_max_distance.insert(0, str(Constants.MAX_BLOCK_DISTANCE))
        self.entry_amount.insert(0, "1")

    def events_register(self):
        """按键事件绑定"""
        self.fly_mode_btn.bind('<Button-1>', lambda c=None: self.switch_fly_mode())
        self.teleport_origin_btn.bind('<Button-1>', lambda c=None: self.teleport_to_origin())
        self.teleport_btn.bind('<Button-1>', lambda c=None: self.teleport())
        self.get_item_btn.bind('<Button-1>', lambda c=None: self.get_item())
        self.speed_btn.bind('<Button-1>', lambda c=None: self.modify_speed())
        self.max_distance_btn.bind('<Button-1>', lambda c=None: self.modify_max_distance())
        self.through_walls_btn.bind('<Button-1>', lambda c=None: self.modify_through_walls())

    def modify_max_distance(self):
        """修改玩家最大触碰范围事件"""
        try:
            Constants.MAX_BLOCK_DISTANCE = int(self.entry_max_distance.get())
            logger.info(f"玩家最大触碰范围修改为{Constants.MAX_BLOCK_DISTANCE}")
        except ValueError:
            logger.error("请输入数字！")

    def modify_speed(self):
        """修改玩家移动速度事件"""
        try:
            Constants.MOVE_SPEED = int(self.entry_speed.get())
            logger.info(f"玩家移动速度修改为{Constants.MOVE_SPEED}")
        except ValueError:
            logger.error("请输入数字！")

    # 创建 tkinter 调试窗口
    @classmethod
    def create_debug_window(cls, **kwargs):
        debug_window = cls(kwargs)
        debug_window.root.mainloop()

    def teleport_to_origin(self):
        """传送回原点事件"""
        origin = [0, 75.0, 0]
        self.kwargs['camera'].transform.position = np.array(origin)
        logger.info(f"传送回原点{origin}成功")

    def modify_through_walls(self):
        """修改墙壁穿透事件"""
        if self.through_walls_mode.get():
            self.through_walls_text.set("关闭墙壁穿透")
            Constants.ThroughWalls = False
        else:
            self.through_walls_text.set("开启墙壁穿透")
            Constants.ThroughWalls = True
        logger.info(f"墙壁穿透修改为:{Constants.ThroughWalls}")

    def switch_fly_mode(self):
        """切换飞行模式事件"""
        if self.fly_mode.get():
            self.mode_text.set("正常移动模式")
            Constants.FLY_MODE = False
        else:
            self.mode_text.set("飞行移动模式")
            Constants.FLY_MODE = True
        logger.info(f"行动模式切换为:{Constants.FLY_MODE}")

    def get_item(self):
        """获取物品事件"""
        item_id, item_amount = self.entry_id.get(), self.entry_amount.get()
        if not item_id.isdigit() or not item_amount.isdigit():
            return
        if self.kwargs['ui_manager'].player_inventory_data.add_item(int(item_id), int(item_amount)):
            logger.info(f"成功给予{item_amount}个ID:{item_id}物品")
        else:
            self.entry_id.delete(0, tk.END)
            self.entry_id.insert(0, "物品不存在！")

    def teleport(self):
        """传送事件"""
        try:
            x, y, z = self.entry_x.get(), self.entry_y.get(), self.entry_z.get()
            self.kwargs['camera'].transform.position = np.array([float(x), float(y), float(z)])
            logger.info(f"传送到坐标{x}, {y}, {z}成功")
        except ValueError:
            logger.error("请输入数字类型的数据！")

    # 禁止关闭窗口
    @staticmethod
    def disable_close():
        """禁止关闭窗口"""
        pass  # 什么都不做，阻止关闭


def start_debug_window(daemon=True, **kwargs):
    # 启动 tkinter 调试窗口在子线程
    debug_thread = threading.Thread(
        target=DebugWindow.create_debug_window,
        kwargs=kwargs
    )
    debug_thread.daemon = daemon  # 守护线程，主程序退出自动关闭
    debug_thread.start()


if __name__ == '__main__':
    start_debug_window(daemon=False)
    # print(get_screen_resolution())
